import fs from 'fs';
import path from 'path';
import axios from 'axios';
import CircularJSON from 'circular-json';

const CACHE_EXPIRY_MS = 30 * 60 * 1000; // 30分钟

const cache = {}; 

function getCache(roleid, type = 'index', folderPath) {
  if (cache[roleid] && cache[roleid].type === type) {
    const { data, timestamp } = cache[roleid];
    const currentTime = Date.now();
    if (currentTime - timestamp <= CACHE_EXPIRY_MS) {
      return data;
    } else {
      delete cache[roleid];
    }
  }
  const filePath = path.join(folderPath, `${roleid}.yaml`);
  if (fs.existsSync(filePath)) {
    try {
      const fileData = fs.readFileSync(filePath, 'utf8');
      const parsedData = CircularJSON.parse(fileData);
      const { timestamp } = parsedData;
      const currentTime = Date.now();
      if (currentTime - timestamp <= CACHE_EXPIRY_MS) {
        cache[roleid] = parsedData; 
        return parsedData.data;
      } else {
        fs.unlinkSync(filePath); 
      }
    } catch (error) {
      console.error('寄:', error);
    }
  }
  return null; // 没有缓存数据或缓存过期
}

async function upcache(roleid, data, type, folderPath) {
  const timestamp = Date.now();
  let retcode = 1; 
  if (data && data.retcode === 0) {
    retcode = 0; // 成功
  } else {
    // this.e.reply(data.message);
    console.error('寄寄:', data.message);
  }
  // 只有在成功时才写入文件
  if (retcode === 0) {
     const filePath = path.join(folderPath, `${roleid}.yaml`);
    try {
       fs.writeFileSync(filePath, CircularJSON.stringify({ data, timestamp, type }, null, 2), 'utf8');
      } catch (error) {
        console.error('寄寄:', error);
     }
    }
  }
// 下载图片并保存到本地
async function downloadimage(url, filePath) {
  const writer = fs.createWriteStream(filePath);

  const response = await axios({
    url,
    method: 'GET',
    responseType: 'stream',
  });

  response.data.pipe(writer);

  return new Promise((resolve, reject) => {
    writer.on('finish', resolve);
    writer.on('error', reject);
  });
}

async function createfold() {
  const baseDir = path.join('./plugins/qiqi-plugin/resources', 'BH3');
  const baseDir1 = path.join('./plugins/qiqi-plugin/data', 'BH3data');
  const avatarDir = path.join(baseDir, 'AvatarIcon');
  const stigmataDir = path.join(baseDir, 'StigmataIcons');
  const weaponDir = path.join(baseDir, 'WeaponIcons');
  const bossDir = path.join(baseDir, 'BOSS');
  const ef = path.join(baseDir, 'EF');
  const vk = path.join(baseDir, 'valkyrie');
  const bfdata = path.join(baseDir1, 'bf');
  const gwdata = path.join(baseDir1, 'godWar');
  const indexdata = path.join(baseDir1, 'index');
  const nb2data = path.join(baseDir1, 'newabyss');
  const vk1data = path.join(baseDir1, 'valkyrie');
  const wk1data = path.join(baseDir1, 'weekly');
  
  // 检查并创建目录
  if (!fs.existsSync(baseDir)) {
    console.log('创建中');
    fs.mkdirSync(baseDir, { recursive: true });
  }

  if (!fs.existsSync(avatarDir)) {
    fs.mkdirSync(avatarDir, { recursive: true });
  }

  if (!fs.existsSync(stigmataDir)) {
    fs.mkdirSync(stigmataDir, { recursive: true });
  }

  if (!fs.existsSync(weaponDir)) {
    fs.mkdirSync(weaponDir, { recursive: true });
  }

  if (!fs.existsSync(bossDir)) {
    fs.mkdirSync(bossDir, { recursive: true });
  }

  if (!fs.existsSync(ef)) {
    fs.mkdirSync(ef, { recursive: true });
  }
  if (!fs.existsSync(vk)) {
    fs.mkdirSync(vk, { recursive: true });
  }
  if (!fs.existsSync(bfdata)) {
    fs.mkdirSync(bfdata, { recursive: true });
  }
  if (!fs.existsSync(gwdata)) {
    fs.mkdirSync(gwdata, { recursive: true });
  }
  if (!fs.existsSync(indexdata)) {
    fs.mkdirSync(indexdata, { recursive: true });
  }
  if (!fs.existsSync(nb2data)) {
    fs.mkdirSync(nb2data, { recursive: true });
  }
  if (!fs.existsSync(vk1data)) {
    fs.mkdirSync(vk1data, { recursive: true });
  }
  if (!fs.existsSync(wk1data)) {
    fs.mkdirSync(wk1data, { recursive: true });
  }
}
export { getCache, upcache, downloadimage, createfold};